import json
import re
from http.client import responses

import redis
from django.contrib.auth import login
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.mail import send_mail
from django.db import transaction
from django.http import JsonResponse

from django.views import View
from django_redis import get_redis_connection

from apps.users import utils
from apps.users.models import User
from meiduo_shop.settings import EMAIL_HOST_USER


# Create your views here.
class UsernamecountView(View):
    def get(self, request,username):
        #利用类视图添加检测用户名是否重名逻辑判断
        count = User.objects.filter(username=username).count()
        return  JsonResponse({'code':0,'count':count,'errmsg':'ok'})
class MobilecountView(View):
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code':0,'count':count,'errmsg':'ok'})
class RegisterView(View):
    def post(self,request):
        try:
            with transaction.atomic():#保证事务一致性
                body_dict = json.loads(request.body.decode())
                username = body_dict.get('username')
                password = body_dict.get('password')
                password2 = body_dict.get('password2')
                mobile = body_dict.get('mobile')
                allow = body_dict.get('allow')
                sms_code=body_dict.get('sms_code')
                # 检测设否有空值
                if not all([username, password, password2, mobile]):
                    return JsonResponse({'code': 400, 'errmsg': '缺少参数'})
                if not allow:
                    return JsonResponse({'code': 400, 'errmsg': '请勾选同意协议'})
                if password != password2:
                    return JsonResponse({'code': 400, 'errmsg': '前后密码输入不一致'})
                if not re.match(r'^1[3-9]\d{9}$', mobile):
                    return JsonResponse({'code': 400, 'errmsg': '手机号输入格式错误'})
                if not re.match(r'^[0-9A-Za-z_-]{5,20}$', username):
                    return JsonResponse({'code': 400, 'errmsg': '用户名输入格式错误'})
                if not re.match(r'^.{8,20}$', password):
                    return JsonResponse({'code': 400, 'errmsg': '密码输入格式错误'})
                # User.objects.create_user(username=username,password=password,mobile=mobile)
                # 连接redis验证短信验证码是否正确
                redis_cli = get_redis_connection('code')
                sms_data = redis_cli.get(mobile)
                if sms_data is None:
                    return JsonResponse({'code': 400, 'errmsg': '短信验证码过期'})
                if sms_code != sms_data.decode():
                    return JsonResponse({'code': 400, 'errmsg': '短信验证码输入错误'})
                # 上述代码插入数据时密码自动加密
                user=User.objects._create_user(username=username, password=password, mobile=mobile, email=None)
                #配置session状态保持，向redis数据库写入信息
                login(request,user)
                return JsonResponse({'code': 0, 'errmsg': 'ok'})
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': str(e)})
class LoginView(View):
    def post(self,request):
        #1.获取数据
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        #2.检查数据
        if not all([username, password]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        if re.match(r'^1[3-9]\d{9}$', username):
            #USERNAME_FIELD字段是查询数据库时所用
            #实现用户多信息登录
            User.USERNAME_FIELD='mobile'#手机号登录
        #3.校验参数,利用django提供的校验方法
        # user = User.objects.get(username=username, password=password)注意密码要加密
        from django.contrib.auth import authenticate, login
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})
        #4.状态保持
        login(request,user)
        #5.是否保持登录状态
        if remembered:
            request.session.set_expiry(None)
        else:
            #浏览器关闭时session过期
            request.session.set_expiry(0)
        response= JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)
        return response
from django.contrib.auth import logout
class LogoutView(View):
    def delete(self,request):
        #删除session信息
        logout(request)
        response= JsonResponse({'code': 0, 'errmsg': 'ok'})
        #删除cookie信息
        response.delete_cookie('username')
        return response
from utils.views import LoginRequiredJsonMixin
class CenterView(LoginRequiredJsonMixin,View):
    def get(self, request):
        #request.user就是已经登录的用户的信息（登录用户信息可以用login(request,user)保存
        #request.user内容源于中间件
        #系统会进行判断，若我们已经登录request.user会返回登录用户的对象
        #若用户没有登录request.user返回AnonymousUser()用户匿名对象
        info_data={
            'username':request.user.username,
            'mobile':request.user.mobile,
            'email':request.user.email,
            'email_active':request.user.email_active,
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok','info_data':info_data})
# class CenterView(View):
#     def get(self, request):
#         user=request.COOKIES.get('username')
#         if not user:
#             return JsonResponse({'code': 0, 'errmsg': '用户未登录'})
#         info_data={
#             'username':request.user.username,
#             'mobile':request.user.mobile,
#             'email':request.user.email,
#             'email_active':request.user.email_active,
#         }
#         return JsonResponse({'code': 0, 'errmsg': 'ok','info_data':info_data})
class EmailView(LoginRequiredJsonMixin,View):
    def put(self, request):
        data = json.loads(request.body.decode())
        email = data.get('email')
        if not email:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 0, 'errmsg': '参数格式错误'})
        #保存用户邮件信息
        user=request.user
        user.email=email
        user.save()
        #加密的数据
        token = utils.varify_email(user.id)
        verify_url="http:www.meiduo.site:8080/success_verify_email.html"
        html_message = f"点击下面的激活按钮激活邮箱<a href='{verify_url}?token={token}'>激活</a>"
        # 异步发送验证邮件
        from celery_tasks.emails import tasks
        #定义参数
        subject = '每多商城激活邮件'
        message = ''
        from_email = EMAIL_HOST_USER
        recipient_list = ['15612383794@163.com']
        html_message = html_message
        #celery可序列化对象为json数据，传入的参数必须可序列化，不能是对象
        tasks.send_email.delay(subject,message,from_email,recipient_list,html_message)
        return JsonResponse({'code': 0, 'errmsg': 'ok'})